#coding: utf-8
from struct import calcsize, pack, unpack
import Predefine
from Types import IndexTableItem, WordItem

def readfmt(fmt, fp):
    return unpack(fmt, fp.read(calcsize(fmt)))

def readint(fp):
    return readfmt('i', fp)[0]

def readbytes(fp, n):
    return readfmt(str(n)+'s', fp)[0]

class WordDictionary(object):

    def __init__(self):
        self.bReleased = True
        self.indexTable = None
        self.modifyTable = None

    def dump(self):
        print len(self.indexTable), 'items'
        for i in self.indexTable[:10]:
            print '\t', i.nCount, 'wordItems in dict'
            for j in xrange(i.nCount):
                w = i.WordItems[j]
                print '\t  ', w.nWordLen, w.nPOS, w.nFrequency, w.sWord

    def Load(self, fpath, reset=False):
        isSuccess = True
        try:
            self._Load(fpath, reset)
        except Exception, err:
            print err
            isSuccess = False
        return isSuccess

    def _Load(self, fpath, reset=False):
        fp = file(fpath, 'rb')
        self.indexTable = []
        
        for i in xrange(Predefine.CC_NUM):
            indexTableItem = IndexTableItem()
            count = max(0, readint(fp))
            indexTableItem.nCount = count
            
            wordItems = []
            for j in xrange(count):
                wordItem = WordItem()
                
                frequency = readint(fp)   #读取频率 
                wordLength = readint(fp)  #读取词长 
                pos = readint(fp)         #读取词性 
                
                if wordLength > 0:
                    wordItem.sWord = readbytes(fp, wordLength)
                else :
                   wordItem.sWord = ""
                
                #Reset the frequency 
                if reset:
                   wordItem.nFrequency = 0
                else:
                   wordItem.nFrequency = frequency
                
                wordItem.nWordLen = wordLength
                wordItem.nPOS = pos
                
                wordItems.append(wordItem)
            
            indexTableItem.WordItems = wordItems
            self.indexTable.append(indexTableItem)

def test():
    d = WordDictionary()
    d._Load('../Data/BigramDict.dct')
    d.dump()

if __name__ == '__main__':
    test()